package it.mp.acquaalta.widget;

import it.mp.acquaalta.AcquaAlta;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;

public class AcquaAltaAppWidgetProvider extends AppWidgetProvider {

	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

		final int N = appWidgetIds.length;
		SharedPreferences pref = context.getSharedPreferences(AcquaAlta.DATI, Context.MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];

			Intent defineIntent = new Intent(context, AcquaAlta.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, defineIntent, PendingIntent.FLAG_UPDATE_CURRENT);

			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.acquaalta);
			views.setOnClickPendingIntent(R.id.LL_layout, pendingIntent);

			// Tell the AppWidgetManager to perform an update on the current App
			// Widget
			appWidgetManager.updateAppWidget(appWidgetId, views);

			Intent intent = new Intent(context, AcquaAltaService.class);
			intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
			context.startService(intent);
			edit.putBoolean(AcquaAlta.WIDGET_APERTA, true);
		}
		edit.commit();
	}
	@Override
	public void onDisabled(Context context) {
		SharedPreferences pref = context.getSharedPreferences(AcquaAlta.DATI, Context.MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putBoolean(AcquaAlta.WIDGET_APERTA, false);
		edit.commit();

		Intent svc = new Intent(context, AcquaAltaService.class);
		context.stopService(svc);
	}

}